//
//  sort.h
//  Job_Scheduling
//
//  Created by zhangyukun on 2021/4/21.
//

#ifndef sort_h
#define sort_h

#include <stdbool.h>
#include "job_control_block.h"

/*
This head file is to sort the wait list with different standard such as reach time , need time ,
privilege and response ratio .
**/

#define FCFS_standard 0
#define SJF_standard 1
#define HPF_standard 2
#define HRRN_standard 3

void sort(struct list_head *head,int standard);
bool set_standard(struct JobControlBlock *elem,struct JobControlBlock *key,int standard);

//give different order dependending on different standard .
bool set_standard(struct JobControlBlock *elem,struct JobControlBlock *key,int standard){
    bool signal = false;
    switch (standard) {
        case FCFS_standard:
            signal = elem->reach_time > key->reach_time;
            break;
        case SJF_standard:
            signal = elem->need_time > key->need_time;
            break;
        case HPF_standard:
            signal = elem->privilege > key->privilege;
            break;
        case HRRN_standard:
            signal = elem->response_ratio < key->response_ratio;
        default:
            break;
    }
    return signal;
}
//sort the wait list with different standard .
void sort(struct list_head *head,int standard){
    struct list_head *curr;                     //to record the position .
    struct list_head *temp = head->next;        //to sort .
    struct list_head *curpos = head->next->next;//to tranverse the list .
    struct JobControlBlock *ptr;
    struct JobControlBlock *ptr_temp;
    while(curpos != head->next){
        curr = curpos->prev;
        ptr = list_entry(curr, struct JobControlBlock, list);
        temp = head->next;
        //use straight insertion sort .
        while(temp != curr){
            ptr_temp = list_entry(temp, struct JobControlBlock, list);
            if(set_standard(ptr_temp, ptr, standard)){
                break;
            }
            temp = temp->next;
        }
        del(curr);
        add(temp->prev, curr);
        curpos = curpos->next;
    }
}
#endif /* sort_h */
